package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.constants.CSConstantsLucene;
import gatperdut.chato.constants.CSConstantsString;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.Action;
import gatperdut.chato.core.interpreter.grammar.comminfo.DocumentInfo;
import gatperdut.chato.lucene.indexer.CMIndexer;
import gatperdut.chato.lucene.search.CMSearcher;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;

public class DocumentAction extends Action {

    public DocumentAction( DocumentInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        checkForRunningCraft();

        Document d = null;
        try {
            d = CMSearcher.getIndexSearcher().doc( getInfo().getDocID() );
        }
        catch ( CorruptIndexException e ) {
            e.printStackTrace();
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
        catch ( IllegalArgumentException e ) {
            getEntityController().tx( "That document does not exist." );
            return CommandExecutionResult.OK;
        }

        StringBuilder sb = new StringBuilder( CSConstantsString.NEWLINE + d.get( CSConstantsLucene.FIELD_TITLE ) + CSConstantsString.NEWLINE
                + CSConstantsString.NEWLINE );
        int pos = 0;
        String[] contentFields = CMIndexer.getContentFieldsByDocType( d.get( CSConstantsLucene.FIELD_TOPIC ) );
        for ( String s : contentFields ) {
            pos++;
            sb.append( d.get( s ) );
            if ( pos < contentFields.length ) {
                sb.append( CSConstantsString.NEWLINE );
            }
        }

        Map<Integer, Document> related = CMSearcher.getRelatedDocuments( d.getValues( CSConstantsLucene.FIELD_RELATED ) );
        if ( !related.isEmpty() ) {
            sb.append( CSConstantsString.NEWLINE + "See also:" + CSConstantsString.NEWLINE );
            for ( Entry<Integer, Document> entry : related.entrySet() ) {
                sb.append( "<" + entry.getKey() + "> - " + entry.getValue().get( CSConstantsLucene.FIELD_TITLE ) + CSConstantsString.NEWLINE );
            }
        }

        getEntityController().tx( sb.toString() );

        return CommandExecutionResult.OK;
    }

    @Override
    public boolean interruptsCrafting() {
        return false;
    }

    @Override
    public DocumentInfo getInfo() {
        return (DocumentInfo) super.getInfo();
    }

}
